package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Measurement;
import model.Sensor;
import model.Video;
import DAO.MeasurementsDao;
import DAO.SensorDao;
import DAO.VideoDao;
import database.DBManager;

/**
 * Servlet implementation class CameraServlet
 */
public class CameraServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private DBManager myDb;
    
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CameraServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init( ServletConfig servletconfig ) {
		// Initialisatie
		myDb = ( DBManager ) servletconfig.getServletContext().getAttribute( "dbmanager" );
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher view = null;
		if(!isLoggedIn(request)){
			view = request.getRequestDispatcher( "index.jsp" );
		}else{
			Logger.createLog(request);
			ArrayList<Video> videos = new ArrayList<Video>();
			VideoDao v = new VideoDao(myDb);
			videos = v.getVideos();
			request.setAttribute("videos", videos);
			view = request.getRequestDispatcher( "webcam.jsp" );
		}
		request = getWarningInfo(request);
		view.forward( request, response );
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher view = null;
		if(!isLoggedIn(request)){
			view = request.getRequestDispatcher("index.jsp");
		}else if(!gotAuth(request)){
			view = request.getRequestDispatcher("SensorServlet?page=home");
		}else{
			Logger.createLog(request);
			if(request.getParameter("record")!=null){
				if (request.getParameter("record").equalsIgnoreCase("record")) {
					view = handleWebcam(request);
				} else{
					if (request.getParameter("record").equalsIgnoreCase("stop")) {
						HttpSession session = request.getSession();
						session.setAttribute("recording", "false");

						Runtime.getRuntime()
								.exec("cmd /c taskkill /IM vlc2.exe /f");
						ArrayList<Video> videos = new ArrayList<Video>();
						VideoDao v = new VideoDao(myDb);
						videos = v.getVideos();
						request.setAttribute("videos", videos);
						view = request.getRequestDispatcher("webcam.jsp");
					}
				}
				if (request.getParameter("record").equalsIgnoreCase("verander")) {
					ArrayList<Video> videos = new ArrayList<Video>();
					VideoDao v = new VideoDao(myDb);
					
					v.editVideo(Long.parseLong( request.getParameter("title")), request.getParameter("description") );
					
					videos = v.getVideos();
					request.setAttribute("videos", videos);
					view = request.getRequestDispatcher("webcam.jsp");
				}
			}
		}
		request = getWarningInfo(request);
		view.forward(request, response);
	}

	private RequestDispatcher handleWebcam(HttpServletRequest request) {
		RequestDispatcher view;
		HttpSession session = request.getSession();
		session.setAttribute("recording", "true");
		try {
			// Kevin PC
			// String cmd =
			// "cmd /c  \"D:\\MijnDocumenten\\school\\INTI3e\\webfarm\\WebContent\\bat\\vlcOpname.bat\"";
			// Server
			long filename1 = System.currentTimeMillis();
			
			String cmd = "cmd /c cd \""+ "C:\\Program Files\\VideoLAN\\VLC2" + "\" & C: & vlc2 http://localhost:8080/stream.flv --demux=dump --demuxdump-file=\"C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\webapps\\webfarm\\videos\\" + filename1 + ".flv";
			Runtime.getRuntime().exec(cmd);

			VideoDao v = new VideoDao(myDb);
			v.addVideo( filename1, "");
			ArrayList<Video> videos = new ArrayList<Video>();
			videos = v.getVideos();
			request.setAttribute("videos", videos);
			view = request.getRequestDispatcher("webcam.jsp");
		} catch (Exception err) {
			VideoDao v = new VideoDao(myDb);
			ArrayList<Video> videos = new ArrayList<Video>();
			videos = v.getVideos();
			request.setAttribute("videos", videos);
			view = request.getRequestDispatcher("webcam.jsp");
			err.printStackTrace();
			System.err.println("camera exception");
		}
		
		return view;
	}
	
	private boolean isLoggedIn(HttpServletRequest request){
		HttpSession session = request.getSession();
		boolean loggedIn = false;
		if(session.getAttribute("logged") != null){
			if(session.getAttribute("logged").equals("true")){
				loggedIn = true;
			}
		}
		return loggedIn;
	}
	
	private boolean gotAuth(HttpServletRequest request){
		HttpSession session = request.getSession();
		boolean gotAuth = false;
		if(session.getAttribute( "rollID" ) != null){
			int rollId = (Integer) session.getAttribute("rollID");
			if(rollId == 1){
				gotAuth = true;
			}
		}
		return gotAuth;
	}
	
	private long getTime(){
//		int year = Calendar.getInstance().get(Calendar.YEAR) 
//		int month = Calendar.getInstance().get(Calendar.MONTH) 
//				+ (Calendar.getInstance().get(Calendar.DAY_OF_MONTH) + 1)
//				+ Calendar.getInstance().get(Calendar.HOUR_OF_DAY) 
//				+ Calendar.getInstance().get(Calendar.MINUTE) +"";
		
		long time = System.currentTimeMillis();
		
		
		return time;
	}
	
	private HttpServletRequest getWarningInfo(HttpServletRequest request){
		MeasurementsDao md = new MeasurementsDao(myDb);
		ArrayList<Measurement> latestMeasurements = new ArrayList<Measurement>();
		for(int i = 1; i <= 5; i++){
			Measurement measurement = md.getLatestMeasurementByID(i);
			if(measurement != null){
				latestMeasurements.add(measurement);
			}
		}
		SensorDao sdao = new SensorDao(myDb);
		ArrayList<Sensor> sensors = sdao.getSensors();
		request.setAttribute("sensorsmax", sensors);
		request.setAttribute("latestMeasurements", latestMeasurements);
		return request;
	}
}
